<?php

namespace Admin\Model;

use Think\Model;
use ORG\File as AA;

class BackupModel extends Model
{
	// 查询数据后格式化数据
	protected function _after_find(&$result, $options) {}
	// 查询数据后回调
	protected function _after_select(&$result, $options) {}
	public function dbList() {
		$result = mysql_list_tables( C( 'DB_NAME' ) );
		if (! $result) {
			print "DB Error, could not list tables\n";
			print 'MySQL Error: ' . mysql_error();
			exit();
		}
		$data = array();
		$i = 1;
		while ( $row = mysql_fetch_row( $result ) ) {
			$data[$i ++] = $row[0];
		}
		mysql_free_result( $result );
		return $data;
	}
	public function dobackup($ids, $filesize) {
		$filesize = intval( $filesize );
		$file = 'Addons/Backup/data/';
		$random = mt_rand( 1000, 9999 );
		$sql = '';
		$p = 1;
		$MM = new AA();
		foreach ( $ids as $table ) {
			$rs = D( str_replace( C( 'DB_PREFIX' ), '', $table ) );
			$array = $rs->select();
			$sql .= "TRUNCATE TABLE `$table`;\n";
			foreach ( $array as $value ) {
				$sql .= $this->insertsql( $table, $value );
				if (strlen( $sql ) >= $filesize * 1000) {
					$filename = $file . date( 'Ymd' ) . '_' . $random . '_' . $p . '.sql';
					$MM->write_file( $filename, $sql );
					$p ++;
					$sql = '';
				}
			}
		}
		if (! empty( $sql )) {
			$filename = $file . date( 'Ymd' ) . '_' . $random . '_' . $p . '.sql';
			return $MM->write_file( $filename, $sql );
		} else
			return false;
	}
	// 生成SQL备份语句
	function insertsql($table, $row) {
		$sql = "INSERT INTO `{$table}` VALUES (";
		$values = array();
		foreach ( $row as $value ) {
			$values[] = "'" . mysql_real_escape_string( $value ) . "'";
		}
		$sql .= implode( ', ', $values ) . ");\n";
		return $sql;
	}
}